<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/9
 * Time: 下午4:37
 */

namespace Biz\service;

use Biz\cache\AllShopCategory as cAllShopCategory;
use Biz\model\ShopCarouselBanner;
use Biz\model\ShopCategoryClassify;
use Biz\model\ShopCommissionRate as mShopCommissionRate;
use Biz\model\wiki\BrandArea as mBrandArea;
use Biz\model\wiki\BrandAreaModule as mBrandAreaModule;
use Biz\service\ShopCommissionRate as sShopCommissionRate;
use Biz\tools\BizUrl;
use Biz\tools\Link;
use Doraemon\model\Category as mCategory;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\service\Category as sCategory;
use Doraemon\tools\LinkFormat;

class Category
{

    private static $err_msg = '';


    public static function getShopSupportList($uid, $categoryId = 0, $categories = null)
    {
        $supportList = is_null($categories) ? sShopCommissionRate::getShopSupportCategoryList($uid) : $categories;

        if (0 == $categoryId) {
            return array_map(function ($v) {
                $data = [
                    'id' => $v['cate_id'],
                    'title' => $v['cate_name'],
                    'pid' => 0,
                ];
                return $data;
            }, $supportList);
        }

        foreach ($supportList as $key => $data) {

            if ($categoryId == $data['cate_id']) {
                if (!isset($data['children'])) {
                    return [];
                }

                return array_map(function ($v) use ($categoryId) {
                    $data = [
                        'id' => $v['cate_id'],
                        'title' => $v['cate_name'],
                        'pid' => $categoryId
                    ];
                    return $data;
                }, $data['children']);
            } else {
                if (empty($data['children'])) {
                    continue;
                }
                return self::getShopSupportList($uid, $categoryId, $data['children']);
            }
        }

    }

    public static function getShopSpuortTreeListByCateId($categoryId, $SuppotTreeList)
    {
        foreach ($SuppotTreeList as $categoryList) {
            if ($categoryList['cate_id'] == $categoryId) {
                return isset($categoryList['children']) ? $categoryList['children'] : [];
            } else if (isset($categoryList['children'])) {
                $result = self::getShopSpuortTreeListByCateId($categoryId, $categoryList['children']);
                if ($result) {
                    return $result;
                }
            }
        }

        return [];
    }

    public static function getShopSupportTreeList($uid, &$categories = null)
    {
        $supportList = is_null($categories) ? sShopCommissionRate::getShopSupportCategoryList($uid) : $categories;

        if (empty($supportList)) {
            return [];
        }

        foreach ($supportList as &$category) {
            if (!isset($category['children'])) {
                continue;
            }

            $secondIds = array_column($category['children'], 'cate_id');

            $groups = [];
            $thirds = mCategory::getChildrenById($secondIds, [
                'father_id',
                'id(cate_id)',
                'deep',
                'cate_name'
            ]);

            if (!empty($thirds)) {

                foreach ($thirds as $value) {
                    $data = [
                        'cate_id' => $value['cate_id'],
                        'father_id' => $value['father_id'],
                        'cate_name' => $value['cate_name'],
                        'deep' => $value['deep']
                    ];
                    $groups[$value['father_id']][] = $data;
                }

                $category['children'] = array_map(function ($val) use ($groups, $uid) {
                    if (isset($groups[$val['cate_id']])) {
                        $val['children'] = $groups[$val['cate_id']];

                    }
                    return $val;

                }, $category['children']);


                if (!empty($category['children'])) {

                    $category['children'] = self::getShopSupportTreeList($uid, $category['children']);

                }

            }

        }

        return is_null($categories) ? array_values($supportList) : $supportList;
    }

    /**
     * categoryId传任意一级分类ID，返回该级分类的梯队分级信息
     *
     * 且第 1、2极分类要在商家支持的分类列表中
     * */
    public static function mgtGetSupportTreeInfo($uid, $categoryId, $data = [])
    {
        if (empty($categoryId)) {
            return [];
        }

        $categoryInfo = mCategory::getCataInfoById($categoryId);

        $data[$categoryInfo['deep']] = $categoryInfo;

        if ($categoryInfo['deep'] != 1) {
            return self::mgtGetSupportTreeInfo($uid, $categoryInfo['father_id'], $data);
        }

        //取2级分类Id如果二级没有，则取1级
        $cateId = isset($data[2]['id']) ? $data[2]['id'] : $data[1]['id'];


        //查询分类列表是否在支持的分类中
        $supportCheck = mShopCommissionRate::checkSupportByCategoryIds($uid, $cateId);

        if (!$supportCheck) {
            return [];
        }
        $data = array_map(function ($v) {
            $data = [
                'id' => $v['id'],
                'name' => $v['cate_name']
            ];
            return $data;
        }, $data);

        ksort($data);

        return [
            'list' => $data,
            'strtree' => implode('>', array_column($data, 'name')),
        ];
    }


    public static function mgtCheckSupportByThirdId($uid, $thirdCategoryId)
    {
        $category = mCategory::getCataInfoById($thirdCategoryId);

        if (empty($category)) {
            return false;
        }

        if ($category['deep'] != '3') {
            return false;
        }

        return mShopCommissionRate::checkSupportByCategoryIds($uid, $category['father_id']);
    }

    public static function checkSupportByCategoryIds($shopId, $categoryIds)
    {
        return mShopCommissionRate::checkSupportByCategoryIds($shopId, $categoryIds);
    }

    public static function mgtGetCategoryInfoTempl($secondCategoryId)
    {

        $res = sCategory::getFatherListByFid($secondCategoryId);

        $category = array_shift($res);

        $data = [
            'material' => !empty($category["material"]) ? explode(",", $category["material"]) : [],
            'size' => !empty($category["size"]) ? explode(",", $category["size"]) : []
        ];

        $data['size'] = array_map(function ($val) {
            $unit = 'cm';
            if (mb_strpos($val, '层数') !== false) {
                $unit = '层';
            }

            if (mb_strpos($val, '容量') !== false) {
                $unit = 'L';
            }

            if (mb_strpos($val, '人数') !== false) {
                $unit = '人';
            }
            if (mb_strpos($val, '面积') !== false) {
                $unit = '㎡';
            }
            $data = [
                'key' => $val,
                'unit' => $unit
            ];
            return $data;
        }, $data['size']);

        return $data;
    }

    public static function setClassifys($classifyName, $goodsCateIds = [], $admin_id)
    {

        if ($goodsCateIds) {

            $classifyName = trim($classifyName);

            if (ShopCategoryClassify::getInfoByName($classifyName)) {
                self::setErrMsg('存在相同名字的分类ID');
                return false;
            }

            $goodsCateIds = array_filter($goodsCateIds);
            $fid = ShopCategoryClassify::addData([
                'classify_name' => $classifyName,
                'admin_id' => $admin_id,
            ]);

            $addDatas = array_map(function ($goodsCateId) use ($fid, $admin_id) {
                return [
                    'parent_id' => $fid,
                    'cate_id' => $goodsCateId,
                    'admin_id' => $admin_id,
                ];
            }, $goodsCateIds);

            return ShopCategoryClassify::addMutiData($addDatas);

        }

        self::setErrMsg('商品类目为空');
        return false;

    }

    public static function getAllClassify($first_classify_id = 0, $allStatus = 0, $getCateInfo = true)
    {

        $map = [];
        if ($first_classify_id) {
            $map['id'] = $first_classify_id;
        }
        $status = ShopCategoryClassify::STATUS_NORMAL;
        if ($allStatus) {
            $status = [
                ShopCategoryClassify::STATUS_NORMAL,
                ShopCategoryClassify::STATUS_HIDE
            ];
        }
        $map['status'] = $status;
        $map['ORDER'] = ['sort' => 'DESC'];
        $map['parent_id'] = 0;

        $classifys = ShopCategoryClassify::selectInfos($map);
        $classify_parent_ids = array_column($classifys, 'id');
        $second_classifys = ShopCategoryClassify::selectClassifyByPids($classify_parent_ids, $status, ['sort' => 'DESC']);

        $cate_parent_ids = [];
        foreach ($second_classifys as $second_classify) {
            $cate_parent_ids = array_merge($cate_parent_ids, array_column($second_classify, 'id'));
        }

        $cate_ids = ShopCategoryClassify::selectCateIdByPids($cate_parent_ids);

        return array_map(function ($classify) use ($second_classifys, $cate_ids, $getCateInfo) {

            return [
                'id' => $classify['id'],
                'classify_name' => $classify['classify_name'],
                'status' => $classify['status'],
                'sort' => $classify['sort'],
                'second_classify_name' => array_map(function ($second_classify) use ($cate_ids, $getCateInfo) {
                    $data = [
                        'id' => $second_classify['id'],
                        'classify_name' => $second_classify['classify_name'],
                        'status' => $second_classify['status'],
                        'sort' => $second_classify['sort'],
                        'icon' => $second_classify['icon'],
                        'icon_url' => $second_classify['icon_url'],
                    ];
                    if ($getCateInfo) {
                        $data['cate_infos'] = ($cate_ids && isset($cate_ids[$second_classify['id']])) ? mCategory::getCategoryList($cate_ids[$second_classify['id']]) : [];
                    }
                    return $data;
                }, isset($second_classifys[$classify['id']]) ? $second_classifys[$classify['id']] : []),
            ];

        }, $classifys);

    }

    public static function getCateIdsByClassifyId($ClassifyId)
    {
        $subClassifyInfos = self::getClassifyByid($ClassifyId);

        if (!isset($subClassifyInfos['cate_info']) && !isset($subClassifyInfos['sub_classifys'])) {
            throw new \Exception('不存在的二级分类ID');
        }

        $cateIds = [];
        if (isset($subClassifyInfos['sub_classifys'])) {
            $allClassifys = self::getAllClassify($ClassifyId);
            foreach ($allClassifys[0]['second_classify_name'] as $secondClassify) {
                $cateIds = array_merge($cateIds, array_column($secondClassify['cate_infos'], 'id'));
            }
        } else {
            $cateIds = array_column($subClassifyInfos['cate_info'], 'id');
        }

        return [
            'classify_name' => $subClassifyInfos['classify_name'],
            'cate_ids' => $cateIds
        ];
    }

    public static function getClassifyByid($id)
    {
        if (!(is_numeric($id) && $id)) {
            throw new \Exception('分类ID不正确');
        }
        $info = ShopCategoryClassify::getInfo($id);
        $cateInfo = ShopCategoryClassify::selectInfos([
            'parent_id' => $id,
            'ORDER' => ['sort' => 'DESC']
        ]);

        $rst = [
            'id' => $info['id'],
            'classify_name' => $info['classify_name'],
            'sort' => $info['sort'],
            'icon_url' => $info['icon_url'],
            'icon' => $info['icon']
        ];

        if ($info['parent_id']) { // 如果是二级分类id
            $rst['cate_info'] = mCategory::getCategoryList(array_column($cateInfo, 'cate_id'));

        } else {
            $rst['sub_classifys'] = array_map(function ($cate) {
                return [
                    'id' => $cate['id'],
                    'title' => $cate['classify_name'],
                    'sort' => $cate['sort'],
                    'icon_url' => $cate['icon_url'],
                    'icon' => $cate['icon']
                ];
            }, $cateInfo);
        }

        return $rst;
//		return [
//			'cate_infos' => mCategory::getCategoryList(array_column($cateInfo, 'cate_id'))
//		];


    }

    public static function getClassifyByIdForApp($id, $isHasAll, $appVersion)
    {

        $classifys = self::getClassifyByid($id);
        if (!($classifys['classify_name'] && isset($classifys['sub_classifys']))) { //分类名为空 或 不存在二级分类 视为 ID 非一级分类ID
            throw new \Exception('不存在的 category_id');
        }
        $result = [
            'id' => $classifys['id'],
            'title' => $classifys['classify_name'],
            'sub_cate' => []
        ];

//        if (version_compare($currentAppVersion, '3.7.0', '>=')) {
        $cateIds = array_column($classifys['sub_classifys'], 'id');
        array_push($cateIds, $id);
        $classifyRes = ShopClassify::quiltGetClassifyByIds($cateIds);
        $secondClassifyBanners = CarouselBanner::getSecondCateBanner($cateIds, date('Y-m-d H:i:s'));
        foreach ($classifys['sub_classifys'] as $sub_classify) {
            $thirdCateArr = $classifyRes[$sub_classify['id']]['classifies'] ?? [];
            $secondSub = [];
            if ($thirdCateArr) {
                $secondSub[] = [
                    'id' => $sub_classify['id'],
                    'title' => '不限',
                ];
                foreach ($thirdCateArr as $row) {
                    $secondSub[] = [
                        'id' => $row['id'],
                        'title' => $row['classify_name']
                    ];
                }
            }
            $result['sub_cate'][] = [
                'id' => $sub_classify['id'],
                'title' => $sub_classify['title'],
                'icon' => $sub_classify['icon_url'],
                'sub_cate' => $secondSub,
                'banner_info' => isset($secondClassifyBanners[$sub_classify['id']]) ? [
                    'id' => $secondClassifyBanners[$sub_classify['id']]['id'],
                    'banner' => $secondClassifyBanners[$sub_classify['id']]['banner'],
                    'link' => $secondClassifyBanners[$sub_classify['id']]['link'],
                    'statType' => ShopCarouselBanner::TYPE_SECOND_CATE . "-" . $secondClassifyBanners[$sub_classify['id']]['show_type'],
                    'statSign' => json_encode([
                        'id' => $secondClassifyBanners[$sub_classify['id']]['id'],
                        'weight' => $secondClassifyBanners[$sub_classify['id']]['sort'],
                        't' => 'adClk',
                        'app' => 'mall',
                        'comment' => $secondClassifyBanners[$sub_classify['id']]['comment'] ?: '',
                        'posiSign' => ShopCarouselBanner::TYPE_SECOND_CATE . '-' . $secondClassifyBanners[$sub_classify['id']]['show_type'] . '-' . $secondClassifyBanners[$sub_classify['id']]['sort'],
                    ], JSON_UNESCAPED_UNICODE)
                ] : null
            ];
        }
        if ($isHasAll) {
            $result['sub_cate'] = array_merge([
                [
                    'id' => $classifys['id'],
                    'title' => '全部',
                    'icon' => null,
                    'sub_cate' => [],
                    'banner_info' => isset($secondClassifyBanners[$classifys['id']]) && version_compare($appVersion, "3.12.0", '<') ? [
                        'id' => $secondClassifyBanners[$classifys['id']]['id'],
                        'banner' => $secondClassifyBanners[$classifys['id']]['banner'],
                        'link' => $secondClassifyBanners[$classifys['id']]['link'],
                        'statType' => ShopCarouselBanner::TYPE_SECOND_CATE . "-" . $secondClassifyBanners[$sub_classify['id']]['show_type'],
                    ] : null
                ]
            ], $result['sub_cate']);
        }
//		} else {
//        	$result['sub_cate'] = array_merge([['id' => $id, 'title' => '全部']],$classifys['sub_classifys']);
//		}

        return $result;
    }

    public static function saveClassify($classifyName, $secondClassifyName, $admin_id, $id = 0, $sort = 0)
    {
        $secondClassifyNames = explode(",", $secondClassifyName);

        if ($id) {
            $classifyList = self::getClassifyList($id)[0];
            $addSecondClassify = [];
            $currId = [];
            $currSecondClassifyIDs = array_column($classifyList['sub_classifys'], 'id');
            ShopCategoryClassify::updateClassify([
                'classify_name' => $classifyName,
                'admin_id' => $admin_id,
                'sort' => $sort
            ], ['id' => $id]);
            array_map(function ($secondClassify) use (&$addSecondClassify, &$currId) {
                $secondClassify = trim($secondClassify);
                $secondClassify = explode(' ', $secondClassify);
                if (!isset($secondClassify[1])) {
                    array_push($addSecondClassify, $secondClassify[0]);
                } else {
                    array_push($currId, $secondClassify[1]);
                }
            }, $secondClassifyNames);

            $delId = array_diff($currSecondClassifyIDs, $currId);

            ShopCategoryClassify::updateClassify(['status' => ShopCategoryClassify::STATUS_DELETE], ['id' => $delId]);

            $secondClassifyNames = $addSecondClassify;

        } else {
            $id = ShopCategoryClassify::addData([
                'classify_name' => $classifyName,
                'admin_id' => $admin_id,
                'sort' => $sort
            ]);
        }

        $data = array_map(function ($secondClassifyName) use ($id, $admin_id) {
            return [
                'classify_name' => $secondClassifyName,
                'parent_id' => $id,
                'admin_id' => $admin_id,
            ];
        }, $secondClassifyNames);


        ShopCategoryClassify::addMutiData($data);


        return $id;
    }

    public static function getClassifyList($classifyId = 0)
    {
        $map = [];
        if ($classifyId) {
            $map['id'] = $classifyId;

        } else {
            $map['parent_id'] = 0;
        }

        $classifysList = ShopCategoryClassify::selectInfos($map);

        $classifysList = array_map(function ($classify) {
            $rst = [];
            $rst['id'] = $classify['id'];
            $rst['classify_name'] = $classify['classify_name'];
            $rst['sort'] = $classify['sort'];
            $sub_classifys = ShopCategoryClassify::selectInfos(['parent_id' => $classify['id']]);

            $rst['sub_classifys'] = array_map(function ($sub_classify) {
                return [
                    'id' => $sub_classify['id'],
                    'classify_name' => $sub_classify['classify_name']
                ];
            }, $sub_classifys);

            return $rst;
        }, $classifysList);


        return $classifysList;
    }


    public static function setErrMsg($err_msg = '')
    {
        self::$err_msg = $err_msg;

    }


    public static function getErrMsg()
    {
        return self::$err_msg;
    }

    public static function getShowCategoryList($category = 0)
    {
        $results = $result = [];
        if ($category > 0) {
            $where = [
                'area_status' => mBrandArea::STATUS_NORMAL,
                'OR' => [
                    'pid' => mBrandArea::getOneByWhere(['category' => $category], 'id'),
                    'AND' => [
                        'category' => $category,
                    ],
                ],
                'ORDER' => ['sort' => 'ASC']
            ];
        } else {
            $where = [
                'area_status' => mBrandArea::STATUS_NORMAL,
                'ORDER' => ['sort' => 'ASC']
            ];
        }
        $list = mBrandArea::getAllByWhere(
            $where,
            [
                'id',
                'pid',
                'sort',
                'title',
                'category'
            ]
        );
        if (!empty($list)) {
            $ids = array_column($list, 'id');
            $adv = mBrandAreaModule::getAllByWhere(
                [
                    'brand_area_id' => $ids,
                    'module_status' => mBrandArea::STATUS_NORMAL,
                    'ORDER' => ['sort' => 'ASC']
                ],
                [
                    'id',
                    'brand_area_id',
                    'title',
                    'pic_id',
                    'link_type',
                    'link_params',
                    'out_link'
                ]
            );
            $advs = [];
            if (!empty($adv)) {
                foreach ($adv as $_ak => &$_av) {
                    $advs[$_av['brand_area_id']][] = $_av;
                }
            }
            foreach ($list as $_k => &$_v) {
                if ($_v['pid'] == 0) {
                    $result[$_v['id']]['info'] = $_v;
                } else if ($_v['pid'] > 0) {
                    $result[$_v['pid']]['son'][$_v['id']] = $_v;
                    if (isset($advs[$_v['id']])) {
                        $result[$_v['pid']]['son'][$_v['id']]['adv'] = $advs[$_v['id']];
                    }
                }
            }
            foreach ($result as $_key => &$_val) {
                $results[$_key] = [
                    'id' => $_val['info']['id'],
                    'title' => $_val['info']['title'],
                    'banner_info' => (object)[],
                    'list' => [],
                ];
                if (isset($_val['son'])) {
                    $lists = [];
                    foreach ($_val['son'] as $_sk => &$_sv) {
                        $lists[$_sk] = [
                            'title' => $_sv['title'],
                            'sub_cate' => [],
                        ];
                        if (isset($_sv['adv'])) {
                            foreach ($_sv['adv'] as $_ak => &$_av) {
                                $lists[$_sk]['sub_cate'][$_ak] = [
                                    'id' => $_av['id'],
                                    'title' => $_av['title'],
                                    'icon' => $_av['pic_url'],
                                    'link' => BizUrl::formatUrlByClientType(LinkFormat::generateLink($_av['link_type'], $_av['link_params'])['app_template']),
                                ];
                            }
                        }
                    }
                    $results[$_key]['list'] = array_values($lists);
                }
            }
        }
        return current(array_values($results));
    }

    public static function getAllCategoryList()
    {
        $result = [];
        $list = cAllShopCategory::getAllCategory();
        if (!$list) {
            $list = self::getAllClassify(0, 0, false);
            cAllShopCategory::setAllCategory($list);
        }
        $firstIds = array_column($list, 'id');
        //$banners = CarouselBanner::getSecondCateBanner($firstIds, date('Y-m-d H:i:s'));//品牌专区下线
        foreach ($list as $row) {
            $link = LinkFormat::generateSingleLink(LinkConf::LINK_APP_CATEGORIES_DETAIL, [
                'category_id' => $row['id'],
                'sub_category_id' => $row['id']]);
            $cateList = [
                'id' => $row['id'],
                'title' => $row['classify_name'],
                'banner_info' => (object)[],
                'list' => [],
//                'link' => Link::format(Link::LINK_MALL_CATEGORY_GOODS_LIST, json_encode(['category_id' => $row['id'], 'sub_category_id' => $row['id']]))
                'link' => $link
            ];
            /*if (isset($banners[$row['id']]) && $banners[$row['id']]) {
                $bannerInfo = $banners[$row['id']];
                $cateList['banner_info'] = [
                    'id' => $bannerInfo['id'],
                    'banner' => $bannerInfo['banner'],
                    'link' => $bannerInfo['link'],
                    'statType' => ShopCarouselBanner::TYPE_SECOND_CATE . "-" . $bannerInfo['show_type'],
                    'statSign' => json_encode([
                        'id' => $bannerInfo['id'],
                        'weight' => $bannerInfo['sort'],
                        't' => 'adClk',
                        'app' => 'mall',
                        'comment' => $bannerInfo['comment'] ?: '',
                        'posiSign' => $bannerInfo['type'] . '-' . $bannerInfo['show_type'] . '-' . $bannerInfo['sort'],
                    ], JSON_UNESCAPED_UNICODE)
                ];
            }*/ //品牌专区下线
            $list = [];
            foreach ($row['second_classify_name'] as $_k => &$secondInfo) {
                $link = LinkFormat::generateSingleLink(LinkConf::LINK_APP_CATEGORIES_DETAIL, [
                    'category_id' => $row['id'],
                    'sub_category_id' => $secondInfo['id']]);
                $list['sub_cate'][] = [
                    'id' => $secondInfo['id'],
                    'title' => $secondInfo['classify_name'],
                    'icon' => $secondInfo['icon_url'],
                    'link' => $link,
//                    'link' => Link::format(Link::LINK_MALL_CATEGORY_GOODS_LIST, json_encode([
//                        'category_id' => $row['id'],
//                        'sub_category_id' => $secondInfo['id']
//                    ], JSON_UNESCAPED_UNICODE))

                ];
            }
            $cateList['list'][0] = array_merge(['title' => '热门分类'], $list);
            //获取广告位
            /* $adv = self::getShowCategoryList($row['id']);
            if ($adv && $adv['list']) {
                $cateList['list'][1] = current($adv['list']);
            }*/ //品牌专区下线
            $result[] = $cateList;
        }
        /* if ($show = self::getShowCategoryList()) {
             $result = array_merge([$show], $result);
         }*/ //品牌专区下线
        return $result;
    }

}